package com.mskj.p3.dao.imp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.mskj.p3.dao.BlogDao;
import com.mskj.p3.model.Blog;
import com.mskj.p3.model.BlogSet;
import com.mskj.p3.model.PageBean;
import com.mskj.p3.model.User;
import com.mskj.p3.util.SQLPageUtil;

@Repository
public class BlogDaoImp implements BlogDao {
	@Resource
	private JdbcTemplate jt;
	
	@Override
	public boolean postBlog(Blog b) {
		String sql = "insert into tbl_blog values(seq_blog.nextval,?,sysdate,?,?)";
		Object[] params = new Object[]{b.getBinfo(),b.getHid(),b.getUid()};
		int updateRecordNum = jt.update(sql,params);
		return updateRecordNum == 1;
	}

	@Override
	public boolean deleteBlog(Blog b, User u) {
		String sql = "delete from tbl_blog where bid = ? and u_id = ?";
		Object[] params = new Object[]{b.getBid(),u.getUid()};
		int updateRecordNum = jt.update(sql,params);
		return updateRecordNum == 1;
	}

	@Override
	public List<BlogSet> queryBlogSet(User user,PageBean pb) {
		String sql = "select bid,binfo,to_char(btime,'yyyy/mm/dd hh24:mi:ss') btime,hid,u.u_id,uname,purl from tbl_blog b,tbl_user u,tbl_picture p where b.u_id = u.u_id and u.pid = p.pid and hid in (select hid from tbl_choose c,tbl_user u where u.u_id=c.u_id and u.u_id=?) order by btime desc";
		Object[] params = new Object[]{user.getUid()};
//		sql = SQLPageUtil.getPageSql(sql, pb);
		List<BlogSet> blogset = (List<BlogSet>)jt.query(sql,params,new BlogSetBeanMapper());
		return blogset;
	}
	
	private class BlogSetBeanMapper implements RowMapper<BlogSet>{

		@Override
		public BlogSet mapRow(ResultSet rs, int pos) throws SQLException {
			BlogSet bs = new BlogSet();
			bs.setBid(rs.getString("bid"));
			bs.setBinfo(rs.getString("binfo"));
			bs.setBtime(rs.getString("btime"));
			bs.setHid(rs.getString("hid"));
			bs.setUid(rs.getString("u_id"));
			bs.setUname(rs.getString("uname"));
			bs.setPurl(rs.getString("purl"));
			return bs;
		}
		
	}

	@Override
	public List<BlogSet> queryMyBlogSet(User user, PageBean pb) {
		String sql = "select bid,binfo,to_char(btime,'yyyy/mm/dd hh24:mi:ss') btime,hid,u.u_id,uname,purl from tbl_blog b,tbl_user u,tbl_picture p where b.u_id = u.u_id and p.pid=u.pid and u.u_id = ?";
		Object[] params = new Object[]{user.getUid()};
//		sql = SQLPageUtil.getPageSql(sql, pb);
		List<BlogSet> blogset = (List<BlogSet>)jt.query(sql,params,new BlogSetBeanMapper());
		return blogset;
	}

}
